package com.ziytek.web.citizen.service;

import com.ziytek.web.citizen.config.caffeine.CaffeineUtil;
import com.ziytek.web.citizen.model.tcp.rsp.TcpRealTimeResponse;
import com.ziytek.web.citizen.service.itf.LastRealtimeDataQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/***
 * @author fenghx
 *
 */

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RealtimeDataService {

    private final LastRealtimeDataQueryService lastRealtimeDataQueryService;

    public TcpRealTimeResponse getRealtimeDataQuery(String cabinetNo) {
        var rsp = lastRealtimeDataQueryService.queryRealDataTwo(cabinetNo, null, null);

        var response = new TcpRealTimeResponse();
        response.setTopic("realTime");
        response.setCabinetNo(cabinetNo);
        if (null != rsp.getData() && !CollectionUtils.isEmpty(rsp.getData())) {
            response.setData(rsp.getData());
        }
        return response;
    }

    public Map<String, Object> getRealTimeCache(String cabinetNo) {
        var key = CaffeineUtil.CACHE_KEY_TOPIC_REALTIME_QUERY
                + CaffeineUtil.CACHE_KEY_SYMBOL
                + cabinetNo;
        Map<String, CaffeineUtil.CacheObject<?>> map = CaffeineUtil.getAllStartWith(key);
        if (CollectionUtils.isEmpty(map)) {
            return Collections.emptyMap();
        }

        List<Map<String, Object>> result = map.values().stream()
                .filter(v -> v instanceof CaffeineUtil.CacheObject<?> cacheObject
                        && cacheObject.data instanceof Map m)
                .map(v -> (Map<String, Object>) v.data)
                .toList();

        return CollectionUtils.isEmpty(result) ? Collections.emptyMap() : result.getFirst();
    }

}
